import argparse
import yaml
import sys
from pathlib import Path
from mm_story_agent import MMStoryAgent


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='MM Story Agent - End-to-End Video Generation from Long Text or Topic'
    )
    parser.add_argument("--config", "-c", type=str, required=True,
                       help="Path to the configuration YAML file")

    args = parser.parse_args()

    # 检查配置文件是否存在
    config_path = Path(args.config)
    if not config_path.exists():
        print(f"❌ Error: Config file not found: {args.config}")
        sys.exit(1)

    print("="*70)
    print("MM Story Agent - Video Generation System")
    print("="*70)
    print(f"📄 Loading config from: {args.config}")
    
    try:
        # 关键修改：添加 encoding='utf-8' 以支持中文
        with open(args.config, "r", encoding='utf-8') as reader:
            config = yaml.load(reader, Loader=yaml.FullLoader)
        print("✅ Config loaded successfully")
    except UnicodeDecodeError as e:
        print(f"❌ Encoding error: {e}")
        print("💡 Tip: Make sure your YAML file is saved in UTF-8 encoding")
        sys.exit(1)
    except yaml.YAMLError as e:
        print(f"❌ YAML parsing error: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"❌ Error loading config: {e}")
        sys.exit(1)

    # 显示配置摘要
    print("\n📋 Configuration Summary:")
    if 'story_writer' in config:
        input_type = config['story_writer']['params'].get('input_type', 'topic')
        print(f"   - Mode: {input_type}")
        if input_type == 'long_text':
            long_text = config['story_writer']['params'].get('long_text', '')
            preview = long_text[:100].replace('\n', ' ') + '...' if len(long_text) > 100 else long_text
            print(f"   - Long text preview: {preview}")
        else:
            topic = config['story_writer']['params'].get('story_topic', 'N/A')
            print(f"   - Story topic: {topic}")
    
    print("\n" + "="*70)
    print("🚀 Starting MM Story Agent...")
    print("="*70 + "\n")
    
    try:
        # 初始化并运行
        mm_story_agent = MMStoryAgent()
        mm_story_agent.call(config)
        
        print("\n" + "="*70)
        print("✅ Video generation completed successfully!")
        print("="*70)
        
    except KeyboardInterrupt:
        print("\n\n⚠️  Process interrupted by user")
        sys.exit(0)
    except Exception as e:
        print(f"\n❌ Error during execution: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)